tongfusoft.bigFile = {};

tongfusoft.bigFile.options = {

	/**
	 * @property {Boolean} [prepareNextFile=false]
	 * @namespace options
	 * @description 是否允许在文件传输时提前把下一个文件准备好。 对于一个文件的准备工作比较耗时，比如图片压缩，md5序列化。
	 *              如果能提前在当前文件传输期处理，可以节省总体耗时。
	 */
	prepareNextFile : false,

	/**
	 * @property {Boolean} [chunked=false]
	 * @namespace options
	 * @description 是否要分片处理大文件上传。
	 */
	chunked : false,

	/**
	 * @property {Boolean} [chunkSize=5242880]
	 * @namespace options
	 * @description 如果要分片，分多大一片？ 默认大小为5M.
	 */
	chunkSize : 5 * 1024 * 1024,
	/**
	 * @property {Object} [formData={}]
	 * @namespace options
	 * @description 文件上传请求的参数表，每次发送都会发送此对象中的参数。
	 */
	formData : {},

	/**
	 * @property {Object} [fileVal='file']
	 * @namespace options
	 * @description 设置文件上传域的name。
	 */
	fileVal : 'file',

	/**
	 * @property {Object} [fileVal='file']
	 * @namespace options
	 * @description 设置Input file id。
	 */
	fileId : 'file',
	/**
	 * 提交按钮ID
	 */
	picker : 'picker',

	progressMD5 : '正在读取上传的文件,需要几分钟',
	progressUpload : '开始上传文件',
	progressUploadError : '上传文件出错了',
	progressUploadfinish : '文件上传成功',

	url : '',
	completeUpload : '',
	/**
	 * 获取已经完成的碎片
	 */
	finishListUrl : '',
	validateMd5ExistUrl : ''

};

tongfusoft.bigFile.fun = function() {
}
tongfusoft.bigFile.fun.prototype = {
	option : tongfusoft.bigFile.options,
	finishList : [],
	fileData : {
		md5 : '',
		data : [],
		name : '',
		ext : '',
		chunks : '',
		chunk : ''

	},
	_initAjax : function(tf) {
		$("#progress-info").html(tf.option.progressUpload);
		$.each(tf.fileData.data, function(index, item) {
			var isUpload = true;
			for (var i = 0; i < tf.finishList.length; i++) {
				if (item.currentChunk == tf.finishList[i].chunk) {

					isUpload = false;
					break;
				}
			}
			if (isUpload) {
				var formData = new FormData();
				formData.append(tf.option.fileVal, new File([ item.blob ], tf.fileData.name));

				formData.append('md5value', tf.fileData.md5);
				formData.append('chunks', tf.fileData.chunks);
				formData.append('fileName', tf.fileData.name);
				;
				formData.append('chunk', item.currentChunk);
				formData.append('ext', tf.getFileExt(tf.fileData.name));
				$.ajax({
					url : common.getContextPath(tf.option.url),
					type : 'POST',
					cache : false,
					async : false,
					data : formData,
					processData : false,
					contentType : false,
					error : function() {
						toastr["error"]('通讯错误');
						$("#progress-info").html(tf.option.progressUploadError);
						tf.progress(((item.currentChunk) / tf.fileData.chunks) * 100, 'progress-bar-danger')
						$("#" + tf.option.picker).button('reset');
						return false;
					},
					success : function(data) {
						tf.progress(((item.currentChunk + 1) / tf.fileData.chunks) * 100, 'progress-bar-success')
						if (item.currentChunk == (tf.fileData.chunks - 1)) {
							$("#progress-info").html(tf.option.progressUploadfinish);
							$("#" + tf.option.picker).button('reset');
							if (typeof (tf.option.completeUpload) == 'function') {

								tf.option.completeUpload();

							}
						}
					}

				})
			} else {

				tf.progress(((item.currentChunk + 1) / tf.fileData.chunks) * 100, 'progress-bar-success')
				if (item.currentChunk == (tf.fileData.chunks - 1)) {
					$("#progress-info").html(tf.option.progressUploadfinish);
					$("#" + tf.option.picker).button('reset');
					if (typeof (tf.option.completeUpload) == 'function') {

						tf.option.completeUpload();

					}
				}

			}
		})
		
		fileData=null;
	},
	init : function() {

		this._selctFile();
		this._initprogress();

	},
	_selctFile : function() {

		var opt = this.option;
		var tf = this;

		$("#" + opt.fileId).on("change", function() {

			tf.pushNameFiles();
			
			

		});
		$("#" + opt.picker).on("click", function() {
			tf._removeProgress();
			tf._initprogress();
			$(this).button('loading');
			tf.fileData = {};
			tf.fileData.data = [];
			tf.fileMd5(tf)
		
			

		})

	},
	getfinishList : function() {

		var tf = this;
		$.ajax({
			url : common.getContextPath(tf.option.finishListUrl),
			type : 'POST',
			cache : false,
			async : false,
			data : {fileMd5:tf.fileData.md5 },
			
			error : function() {
				toastr["error"]('通讯错误');

				return false;
			},
			success : function(data) {
				if (data.state == 'success') {

					tf.finishList = data.data;
				}

			}

		})

	},

	_initprogress : function() {
		var progressHtml = '<div id="ppId"><br/><span id="progress-info"></span> <div class="progress">'
				+ '<div  id="progress" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 0" class="progress-bar progress-bar-info">'
				+ '</div>' + '</div></div>';

		$("#" + this.option.fileId).after(progressHtml);

	},
	_removeProgress : function() {
		

		$("#ppId").remove();

	},
	progress : function(scale, progress) {

		$("#progress").removeClass();
		$("#progress").addClass("progress-bar " + progress);
		$("#progress").css("width", scale + "%");

	},
	fileMd5 : function(tf) {
		$("#progress-info").html(tf.option.progressMD5);
		var fileReader = new FileReader();
		blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice;
		var file = $("#" + tf.option.fileId)[0].files[0];
		var chunkSize = tf.option.chunkSize;
		var chunks = Math.ceil(file.size / chunkSize);
		tf.fileData.chunks = chunks;
		var currentChunk = 0;
		var bs = fileReader.readAsBinaryString;
		spark = new SparkMD5.ArrayBuffer();
		fileReader.onload = function(ee) {

			var cutFile = {};
			cutFile.currentChunk = currentChunk;
			cutFile.blob = ee.target.result;
			cutFile.name = file.name;
			tf.fileData.data.push(cutFile);

			spark.append(ee.target.result);
			currentChunk++;

			if (currentChunk < chunks) {
				loadNext();
			} else {
				tf.fileData.md5 = spark.end();
				if(tf.validateMd5Exist()){
					
					tf.progress(100, 'progress-bar-success')
					$("#progress-info").html(tf.option.progressUploadfinish);
					$("#" + tf.option.picker).button('reset');
				}else{
					tf._removeProgress();
					tf._initprogress();
					tf.getfinishList();
					tf.pushNameFiles();
					tf._initAjax(tf);
				
				}
			}
		}

		function loadNext() {
			var start = currentChunk * chunkSize, end = start + chunkSize >= file.size ? file.size : start + chunkSize;
			var o = fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
			tf.progress(((currentChunk + 1) / tf.fileData.chunks) * 100, 'progress-bar-info')
		}

		loadNext();
	},
	getFileExt : function(str) {

		var d = /\.[^\.]+$/.exec(str);
		return d;
	},
	pushNameFiles : function() {
		var content = '', files = [];
		var opt = this.option;
		var tf = this;
		if ($("#" + opt.fileId)[0].files === undefined) {
			files[0] = {
				'name' : $("#" + opt.fileId)[0] && $("#" + opt.fileId)[0].value
			};
		} else {
			files = $("#" + opt.fileId)[0].files;
		}

		for (var i = 0; i < files.length; i++) {
			content += files[i].name.split("\\").pop() + ', ';
		}

		if (content !== '') {
			$("#" + opt.fileId + "_name").val(content.replace(/\, $/g, ''));
		} else {
			$("#" + opt.fileId + "_name").val('');
		}
		tf.fileData.name = $("#" + opt.fileId + "_name").val();
		return files;
	},
	validateMd5Exist : function() {

		var tf = this;
		
		
		$.ajax({
			url : common.getContextPath(tf.option.validateMd5ExistUrl),
			type : 'POST',
			cache : false,
			async : false,
			data : {fileMd5:tf.fileData.md5 },
			
			error : function() {
				toastr["error"]('通讯错误');

				return false;
			},
			success : function(data) {
				if (data.code == 'exist') {
					return true;
					
				}else{
					return false;
				}

			}

		})
	}

}
var bigFile = {};
bigFile.create = tongfusoft.bigFile.create = function(option) {

	$.extend(tongfusoft.bigFile.options, option);
	var obj = new tongfusoft.bigFile.fun();
	obj.init();
	return obj;
}